$(function () {
  const api = localStorage.getItem("api") || "";
  let myChart = null; // 将图表实例提到外层
  // 初始化地图
  function initChart(data) {
    if (!myChart) {
      myChart = echarts.init(document.getElementById("map_1"));
    }
    var option = {
        title: {
            text: `${localStorage.getItem("selectedYear")}年农作物各省份产量最多分布情况`,
            left: "center",
            textStyle: {
              color: "#fff",
              fontSize: 28
            },
            subtext: "单位：万吨",
            subtextStyle: {
              color: "#ccc",
              fontSize: 14
            }
          },
      tooltip: {
        trigger: "item",
        formatter: function (params) {
            return `${params.name} : ${params.value || "无数据"}<br/>${params.data.indicator || ""}`;
          },
      },
      series: [
        {
          name: "消费金额",
          type: "map",
          map: "china",
          roam: false,
          label: {
            normal: {
              show: true,
              color: "#fff",
              formatter: function (params) {
                return params.value || "";
              },
            },
            emphasis: {
              show: true,
              color: "#fff",
            },
          },
          itemStyle: {
            normal: {
              areaColor: "#4c60ff",
              borderColor: "#002097",
            },
            emphasis: {
              areaColor: "#293fff",
            },
          },
          data: data, // 使用动态数据
        },
      ],
    };

    myChart.setOption(option);
    window.addEventListener("resize", myChart.resize);
  }

  // 初始化默认数据
  initChart([]);

  // 获取数据函数
  function get_mapData() {


    fetch(api + "/bigscreen/agriculturalyield", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
      },
      body:  JSON.stringify({
        year: localStorage.getItem("selectedYear")
      })
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        const mapdata = data.map(item => ({
            name: item.name,  
            indicator: item.indicator,
            value: item.value  
          }));
         
        initChart(mapdata); // 更新图表数据
      })
      .catch((error) => console.error("请求失败:", error));
  }

  // 立即获取数据
  get_mapData();
});
